require "trifle/ruby/wrappers/exception_payload"

module Trifle
	module Ruby
		class Event < ActiveSupport::Notifications::Event
			attr_accessor :name, :time, :end, :transaction_id, :identifier, :payload, :event_type

			def initialize(name, start, ending, transaction_id, payload)
				super(name, start, ending, transaction_id, Trifle::Ruby::JsonTransform.transform(payload))
			end

			def as_json(options={})
				# payload.request is Enumerable and cant be converted
				self.payload.delete(:request)
				attrs = {
					name: self.name,
					event_type: self.event_type,
					identifier: self.identifier,
					duration: self.duration.round(2),
					payload: self.payload,
					started_at: self.time.to_f,
					finished_at: self.end.to_f
				}
				attrs.delete_if {|k, v| v.nil?}
				attrs.delete_if {|k, v| v.respond_to?(:empty?) and v.empty? }
				attrs
			end

			def stacktrace(stack)
				parsed = []
				stack.each do |line|
					line.gsub!("#{::Rails.root}/", "")
					if /^((?:app|config|lib|test).+?):(\d+)(?::in `(.*)")?/ =~ line
						parsed<< line
					end
				end
				parsed
			end
		end
	end
end
